package com.lzx.adx.report.controller.v1.toutiao;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.enums.TaoBaoCovertToutiaoEnums;
import com.lzx.adx.report.model.toutiao.request.TouTiaoRequest;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.URLEncoderDecoderTool;
import com.lzx.adx.report.util.helper.TouTiaoHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/jl")
@RestController
@Slf4j
public class TouTiaoController {

    @Autowired
    private ReportService reportService;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private ReportMapper reportMapper;

    public static final   String apiDesc="头条-手淘";


    @GetMapping("/report")
    public ResponseEntity report(TouTiaoRequest touTiaoRequest, HttpServletRequest request){

        log.info("接收到【{}】的请求参数为{}",apiDesc, JsonUtils.toJsonString(touTiaoRequest));
        //1.收到监测的数据存储
        ReportDTO reportDTO=reportMapper.toReportDTO(touTiaoRequest);
        reportDTO.setBizRequestId(IdUtil.fastSimpleUUID()+reportDTO.getDspId());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JsonUtils.toJsonString(touTiaoRequest));
        reportDTO.setTraceTime(String.valueOf(System.currentTimeMillis()/1000));
        reportExecutor.execute(()->{
            reportService.saveData(reportDTO);
        });

        AccountDTO accountDTO = AccountLocalCache.getInstance().get(touTiaoRequest.getDspId());

        String resultUrl = TouTiaoHelper.covertUrl(accountDTO, reportDTO);

        log.info("头条-手淘，请求完整的url为{}",resultUrl);
        String result = HttpUtil.get(resultUrl);
        log.info("头条-手淘，响应结果为{}",result);

        return ResponseEntity.ok(new Result());
    }




    @GetMapping("callback")
    public ResponseEntity callBackUrl(String requestId,String transformType) throws Exception {
        log.info("头条接收了大航海，回调信息，请求流水号{},回调类型为{}", requestId, transformType);
        String eventType = TaoBaoCovertToutiaoEnums.getTtCode(transformType);
        if (StringUtils.isBlank(eventType)) {
            log.info("请求流水号{},头条接收了大航海，回调信息，回调类型为{}，不支持", requestId, transformType);
            return ResponseEntity.ok(new Result());
        }
        String event_time = String.valueOf(System.currentTimeMillis());
        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
            reportDTO.setResultType(transformType);
            reportDTO.setResultTime(event_time);
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,transformType);
        } else {
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        //2.从缓存加载配置
        String url = URLEncoderDecoderTool.decodeURL(reportDTO.getCallback());
        String resultUrl = url + "&event_type=" + eventType;
        log.info("账户:{},请求id:{}手淘-头条，请求完整的url为{}", reportDTO.getDspId(), requestId, resultUrl);
        String result = HttpUtil.get(resultUrl);
        log.info("账户:{},请求id:{}手淘-头条，响应结果为{}", reportDTO.getDspId(), requestId, result);
        return ResponseEntity.ok(new Result());
    }
}
